using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using Serilog;

namespace MoonFramework.Net
{
    /// <summary>
    /// 数据流，采用大端模式存储。
    /// </summary>
    public class DataStream : MemoryStream
    {
        // 对象池 (线程安全)
        private static readonly ConcurrentBag<DataStream> Pool = new();
        public static int PoolMaxCount = 200;

        private DataStream()
        {
        }

        /// <summary>
        /// 从对象池中获取 DataStream。
        /// </summary>
        public static DataStream Allocate()
        {
            return Pool.TryTake(out var stream) ? stream : new DataStream();
        }

        public static DataStream Allocate(byte[] bytes)
        {
            var stream = Allocate();
            stream.Write(bytes, 0, bytes.Length);
            stream.Position = 0;
            return stream;
        }

        // 泛型读取方法
        public T ReadT<T>() where T : unmanaged
        {
            int size = Marshal.SizeOf<T>();
            Span<byte> buffer = stackalloc byte[size];
            if (BitConverter.IsLittleEndian)
                buffer.Reverse();
            return MemoryMarshal.Read<T>(buffer);
        }

        // 泛型写入方法
        public void WriteT<T>(T value) where T : unmanaged
        {
            int size = Marshal.SizeOf<T>();
            Span<byte> buffer = stackalloc byte[size];
            MemoryMarshal.Write(buffer, ref value);
            if (BitConverter.IsLittleEndian)
                buffer.Reverse();
            Write(buffer);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Log.Information("DataStream自动释放");
                if (Pool.Count < PoolMaxCount)
                {
                    Position = 0;
                    SetLength(0);
                    Pool.Add(this);
                }
                else
                {
                    base.Dispose(disposing);
                    Close();
                }
            }
        }
    }
}
